/*
 * Powered By [rapid-framework]
 * Csdn Code: generate simple CRUD code in single table.
 * Since 2015 - 2017
 */

BUI.use('common/page');
BUI.use(['common/search', 'bui/overlay', 'bui/grid', 'bui/data', 'bui/form'],
    function (Search, Overlay, Grid, Data, Form) {
        var privileges = sessionStorage.getItem('privileges');
        var privilegeList = privileges.split(',');
        var updatePrivilege = false;
        var addPrivilege = false;
        if (privilegeList.length > 0) {
            for (var i = 0; i < privilegeList.length; i++) {
                if (privilegeList[i] == 'updateMerchantProduct') {
                    updatePrivilege = true;
                    continue;
                }
                if (privilegeList[i] == 'saveMerchantProduct') {
                    addPrivilege = true;
                    continue;
                }
            }
        }
        var hotEnum = {
            "0": "非热门",
            "1": "热门"
        };
        var lived = {
            '0':"作废",
            '1':"有效"
        };
        var TechinalEnum = {
            "0": "非对接",
            "1": "已对接"
        };
        var productTypeEnum = {
            "0": "现金",
            "1": "还信用卡",
            "2": "购物消费"
        };
        // var isHotEnumArray=[{text:'非热门',value:'0'},{text:'热门',value:'1'}];
        // var isHotSelectData = {'enumRenderer':'true','items':isHotEnumArray};
        // $("#isHotSelect").attr('data-select',JSON.stringify(isHotSelectData));
        // var isTechinalEnumArray=[{text:'非对接',value:'false'},{text:'已对接',value:'true'}];
        // var isTechinalData = {'enumRenderer':'true','items':isTechinalEnumArray};
        // $("#isTechnicalSelect").attr('data-select',JSON.stringify(isTechinalData));
        // 查询表单
        var form = new Form.Form({
            srcNode: '#searchForm'
        }).render();
        var onlineStatusEnum=[];
        var onlineStatusJson={};
        $.ajaxSettings.async = false;
        $.getJSON('listAllOnlineStatus',function (onlineStatusData) {
            onlineStatusEnum=onlineStatusData;
            for(var i=0;i<onlineStatusData.length;i++){
                toJson(onlineStatusJson,onlineStatusData[i].value,onlineStatusData[i].text);
            }
        });
        $.ajaxSettings.async = true;
        var selectData = {'enumRenderer':'true','items':onlineStatusEnum};
        $("#onlineStatusSelect").attr('data-select',JSON.stringify(selectData));
        function toJson(array, prop, val) {
            // 如果 val 被忽略
            if (typeof val === "undefined") {
                // 删除属性
                delete array[prop];
            } else {
                // 添加 或 修改
                if (val.length > 0) {
                    array[prop] = val;
                }
            }
        }
        // 定义表头
        if (updatePrivilege) {
            columns = [
                {
                    title: 'id',
                    dataIndex: 'productId',
                    visible: false
                },
                {
                    title: 'merchant_id',
                    dataIndex: 'merchantId',
                    visible: false
                },
                {
                    title: '产品名称',
                    dataIndex: 'productName',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品名称不能为空!']
                        }
                    }
                },
                {
                    title: '竞价',
                    dataIndex: 'bidding',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '竞价不能为空!']
                        }
                    }
                },
                {
                    title: '最高额度',
                    dataIndex: 'productMaxcredit',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',

                        rules: {
                            required: [true, '最高额度不能为空!']
                        }
                    }
                },
                {
                    title: '最低额度',
                    dataIndex: 'productMincredit',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '最低额度不能为空!']
                        }
                    }
                },
                {
                    title: '参考费率',
                    dataIndex: 'productRate',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '参考费率不能为空!']
                        }
                    }
                },
                {
                    title: '参考期限 ',
                    dataIndex: 'productPeriod',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '参考期限 不能为空!']
                        }
                    }
                },
                {
                    title: '申请人数',
                    dataIndex: 'productApplycount',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '申请人数不能为空!']
                        }
                    }
                },
                {
                    title: '产品简介',
                    dataIndex: 'productDesc',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品简介不能为空!']
                        }
                    }
                },
                {
                    title: '产品链接',
                    dataIndex: 'productUri',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品链接不能为空!']
                        }
                    }
                },
                {
                    title: '产品icon',
                    dataIndex: 'productIcon',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品icon不能为空!']
                        }
                    }
                },
                {
                    title: '产品详情',
                    dataIndex: 'productMemo',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品详情不能为空!']
                        }
                    }
                },
                {
                    title: '产品申请条件',
                    dataIndex: 'productApplycondition',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品申请条件不能为空!']
                        }
                    }
                },
                {
                    title: '是否热门贷款',
                    dataIndex: 'hot',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: hotEnum,
                        rules: {
                            required: [true, '是否热门贷款不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(hotEnum)
                },
                {
                    title: '产品类型(0:现金;1还信用卡;2购物消费)',
                    dataIndex: 'productType',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: productTypeEnum,
                        rules: {
                            required: [true, '产品类型(0:现金;1还信用卡;2购物消费)不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(productTypeEnum)
                },
                {
                    title: '产品标签',
                    dataIndex: 'tag',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品标签不能为空!']
                        }
                    }
                },
                {
                    title: '是否技术对接',
                    dataIndex: 'technical',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: TechinalEnum,
                        rules: {
                            required: [true, '是否技术对接不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(TechinalEnum)
                },
                {
                    title: '成功率',
                    dataIndex: 'successRate',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '成功率不能为空!']
                        }
                    }
                },
                {
                    title: '是否有效',
                    dataIndex: 'merchantId',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: lived,
                        rules: {
                            required: [true, '是否有效不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(lived)
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'date',
                        datePicker: {
                            showTime: true
                        },
                        rules: {
                            required: [true, '最后创建时间不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format.datetimeRenderer
                },
                {
                    title: '最后更新时间',
                    dataIndex: 'updateTime',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'date',
                        datePicker: {
                            showTime: true
                        },
                        rules: {
                            required: [true, '最后最后更新时间不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format.datetimeRenderer
                },
                {
                    title: '操作',
                    elCls: 'center',
                    width: 100,
                    renderer: function (value, obj) {
                        return '<span class="grid-command btn-edit">编辑</span>';
                    }
                },{
                    title: 'productBusinessId',
                    dataIndex: 'productBusinessId',
                    visible: false
                },{
                    title: '对接开始时间',
                    dataIndex: 'businessStartDate',
                    visible: false
                },{
                    title: '合同开始时间',
                    dataIndex: 'contractStartDate',
                    visible: false
                },{
                    title: '合同完成时间',
                    dataIndex: 'contractEndDate',
                    visible: false
                },{
                    title: '准备上线时间',
                    dataIndex: 'prepareOnlineDate',
                    visible: false
                },{
                    title: '上线开始时间',
                    dataIndex: 'onlineStartDate',
                    visible: false
                },{
                    title: '下线时间',
                    dataIndex: 'onlineEndDate',
                    visible: false
                },{
                    title: '上线状态',
                    dataIndex: 'onlineStatus',
                    visible: false
                },{
                    title: '备注',
                    dataIndex: 'remarks',
                    visible: false
                }];
        } else {
            columns = [
                {
                    title: 'id',
                    dataIndex: 'productId',
                    visible: false
                },
                {
                    title: 'merchant_id',
                    dataIndex: 'merchantId',
                    visible: false
                },
                {
                    title: '产品名称',
                    dataIndex: 'productName',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品名称不能为空!']
                        }
                    }
                },
                {
                    title: '竞价',
                    dataIndex: 'bidding',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '竞价不能为空!']
                        }
                    }
                },
                {
                    title: '最高额度',
                    dataIndex: 'productMaxcredit',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',

                        rules: {
                            required: [true, '最高额度不能为空!']
                        }
                    }
                },
                {
                    title: '最低额度',
                    dataIndex: 'productMincredit',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '最低额度不能为空!']
                        }
                    }
                },
                {
                    title: '参考费率',
                    dataIndex: 'productRate',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '参考费率不能为空!']
                        }
                    }
                },
                {
                    title: '参考期限 ',
                    dataIndex: 'productPeriod',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '参考期限 不能为空!']
                        }
                    }
                },
                {
                    title: '申请人数',
                    dataIndex: 'productApplycount',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '申请人数不能为空!']
                        }
                    }
                },
                {
                    title: '产品简介',
                    dataIndex: 'productDesc',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品简介不能为空!']
                        }
                    }
                },
                {
                    title: '产品链接',
                    dataIndex: 'productUri',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品链接不能为空!']
                        }
                    }
                },
                {
                    title: '产品icon',
                    dataIndex: 'productIcon',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品icon不能为空!']
                        }
                    }
                },
                {
                    title: '产品详情',
                    dataIndex: 'productMemo',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品详情不能为空!']
                        }
                    }
                },
                {
                    title: '产品申请条件',
                    dataIndex: 'productApplycondition',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品申请条件不能为空!']
                        }
                    }
                },
                {
                    title: '是否热门贷款',
                    dataIndex: 'hot',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: hotEnum,
                        rules: {
                            required: [true, '是否热门贷款不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(hotEnum)
                },
                {
                    title: '产品类型(0:现金;1还信用卡;2购物消费)',
                    dataIndex: 'productType',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: productTypeEnum,
                        rules: {
                            required: [true, '产品类型(0:现金;1还信用卡;2购物消费)不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(productTypeEnum)
                },
                {
                    title: '产品标签',
                    dataIndex: 'tag',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '产品标签不能为空!']
                        }
                    }
                },
                {
                    title: '是否技术对接',
                    dataIndex: 'technical',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: TechinalEnum,
                        rules: {
                            required: [true, '是否技术对接不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(TechinalEnum)
                },
                {
                    title: '成功率',
                    dataIndex: 'successRate',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'text',
                        rules: {
                            required: [true, '成功率不能为空!']
                        }
                    }
                },
                {
                    title: '是否有效',
                    dataIndex: 'merchantId',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'select',
                        items: lived,
                        rules: {
                            required: [true, '是否有效不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format
                        .enumRenderer(lived)
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'date',
                        datePicker: {
                            showTime: true
                        },
                        rules: {
                            required: [true, '最后创建时间不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format.datetimeRenderer
                },
                {
                    title: '最后更新时间',
                    dataIndex: 'updateTime',
                    elCls: 'center',
                    width: 120,
                    editor: {
                        xtype: 'date',
                        datePicker: {
                            showTime: true
                        },
                        rules: {
                            required: [true, '最后最后更新时间不能为空!']
                        }
                    },
                    renderer: BUI.Grid.Format.datetimeRenderer
                }];
        }
        // 行编辑
        // var editing = new Grid.Plugins.RowEditing({
        //   triggerCls: 'btn-edit',
        //   triggerSelected: false
        //
        // });

        var editing = new Grid.Plugins.DialogEditing({
            contentId : 'content1',
            triggerCls : 'btn-edit',
            editor : {
                title : '产品修改',
                width : 850
            }
        });

        // 获取数据
        store = new BUI.Data.Store({
            url: 'listMerchantProduct?field=bidding&direction=desc',
            pageSize: 20,
            autoLoad: true,
            remoteSort: true
        });
        // 获取表格对象
        if (addPrivilege) {
            gridCfg = Search.createGridCfg(columns, {
                plugins: [editing, Grid.Plugins.CheckSelection],
                tbar: { // 添加、删除
                    items: [{
                        btnCls: 'button button-small',
                        text: '<i class="icon-plus"></i>添加',
                        listeners: {
                            'click': addFunction
                        }
                    }, {
                        btnCls: 'button button-small',
                        text: '<i class="icon-refresh"></i>刷新',
                        listeners: {
                            'click': refreshFunction
                        }
                    }]
                }
            });
        } else {
            gridCfg = Search.createGridCfg(columns, {
                plugins: [editing, Grid.Plugins.CheckSelection],
                tbar: {
                    items: [{
                        btnCls: 'button button-small',
                        text: '<i class="icon-refresh"></i>刷新',
                        listeners: {
                            'click': refreshFunction
                        }
                    }]
                }
            });
        }
        // // 触发编辑
        // editing.on('editorshow', function (ev) {
        //   var editor = editing.get('curEditor');
        //   editor.set('errorAlign', {
        //     points: ['br', 'tr'],
        //     offset: [0, 10]
        //   });
        // });
        // 编辑提交
        editing.on('accept', function (ev) {
            var record = editing.get('record');
            // console.log(record);
            if (record.hasOwnProperty("b")) {
                delete record["b"];
            }
            if (record.hasOwnProperty("")) {
                delete record[""];
            }
            if (record.hasOwnProperty("createTime")) {
                delete record["createTime"];
            }
            if (record.hasOwnProperty("updateTime")) {
                delete record["updateTime"];
            }
            var saveUrl = 'updateMerchantProduct';
            jQuery.ajax({
                type: 'POST',
                url: saveUrl,
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(record),
                complete: function (data) {
                    if (data.responseText == "success") { // 删除成功
                        search.load();
                    } else { // 删除失败
                        BUI.Message.Alert('保存失败！');
                    }
                }
            });
        });

        // new Form.HForm({
        //     srcNode: '#J_Form'
        // }).render();

        var dialog = new Overlay.Dialog({
            title: '新增产品',
            width: 650,
            height: 450,
            //配置DOM容器的编号
            contentId: 'content',
            success: function () { //产品保存
                var d = {};
                var a = [];
                var f = false;
                var e = {
                    productName: '产品名称不能空！',
                    productType: '产品类型不能为空!',
                    tag: '标签不能为空！',
                    isTechnical: '是否技术对接不能为空！',
                    conditionType: '条件名称不能为空！',
                    conditionValue: '条件值不能为空！'
                };
                var t = $('#J_Form').serializeArray();
                $.each(t, function () {
                    d[this.name] = this.value;
                });
                console.log(JSON.stringify(d));
                $("#conditionTable").find("tr").each(function () {
                    var tdArr = $(this).children();
                    var condtion_type = tdArr.eq(0).find("select").val();//类别
                    var condition_value = tdArr.eq(1).find("input").val();//金额
                    var item = {
                        conditionType: condtion_type,
                        conditionValue: condition_value
                    };
                    a.push(item);
                });
                d.conditionList = a;
                // alert(BUI.JSON.stringify(d));
                valid(d, e);

                function valid(d, e) {
                    for (var key in d) {
                        console.log(key + ":" + d[key]);
                        if (Array.isArray(d[key])) {
                            for (var o in d[key]) {
                                valid(o, e);
                            }
                        }
                        if (!d[key]) {
                            f = true;
                            alert(e[key]);
                        }
                    }
                }

                if (!f) {
                    var saveUrl = 'saveMerchantProductExt';
                    jQuery.ajax({
                        type: 'POST',
                        url: saveUrl,
                        dataType: 'json',
                        contentType: 'application/json;charset=UTF-8',
                        data: BUI.JSON.stringify(d),
                        complete: function (data) {
                            if (data.responseText == "success") { // 保存成功
                                search.load();
                            } else { // 删除失败
                                BUI.Message.Alert('保存失败！');
                            }
                        }
                    });
                    this.close();
                }

            }
        });

        // 添加记录
        function addFunction() {
            // var newData = {
            //     'productName': ''
            // };
            // store.addAt(newData, 0);
            // editing.edit(newData, 'productName'); // 添加记录后，直接编辑

            dialog.show();
        }

        // 删除选中的记录
        function delFunction() {
            var selections = grid.getSelection();
            delItems(selections);
            store.remove(selections);
        }

        // 刷新
        function refreshFunction() {
            search.load();
        }

        // 删除
        function delItems(items) {
            var ids = "";
            BUI.each(items, function (item) {
                ids += item.productId + ",";
            });
            if (ids.length) {
                BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                    jQuery.ajax({
                        type: 'POST',
                        url: 'removeMerchantProduct',
                        dataType: 'json',
                        data: {
                            'ids': ids
                        },
                        complete: function (data) {
                            if (data.responseText == "success") { // 删除成功
                                search.load();
                            } else { // 删除失败
                                BUI.Message.Alert('删除失败！');
                            }
                        }
                    });
                }, 'question');
            }
        }

        // 查询
        search = new Search({
            store: store,
            autoSearch: true,
            gridCfg: gridCfg
        });
        grid = search.get('grid');
    });

//增加一行
function appendItem() {
    var template = "        <tr>\n"
        + "          <td>\n"
        + "            <select  data-rules=\"{required:true}\" form=\"J_Form\"  name=\"conditionType\" class=\"input-normal\">\n"
        + "              <option value=\"\">——请选择——</option>\n"
        + "              <option value=\"0\">货款金额</option>\n"
        + "              <option value=\"1\">货款期限</option>\n"
        + "              <option value=\"2\">货款类型</option>\n"
        + "              <option value=\"2\">APP描述</option>\n"
        + "            </select>\n"
        + "          </td>\n"
        + "          <td><input name=\"conditionValue\" type=\"text\" form=\"J_Form\" data-rules=\"{required:true}\" class=\"input-normal control-text\"></td>\n"
        + "        </tr>";
    jQuery("#conditionTable").append(template);
}

//删除一行
function deleteItem() {
    jQuery("#conditionTable").children("tr").last().remove();
}

